<?php

namespace app\api\logic;

use app\admin\model\User;
use app\common\exception\LogicException;
use app\common\model\Area;
use think\Exception;

class UserLogic
{
    protected User $model;

    public function __construct()
    {
        $this->model = new User();
    }

    public function getUserInfo($id)
    {
        $userInfo = $this->model
            ->field('id, nickname, mobile, avatar,gender,age,height,weight,constellation,hobby,province_id,city_id')
            ->where(['id' => $id])
            ->find();
        if (!$userInfo) {
            throw new LogicException('用户不存在',400);
        }
        $areaModel = new Area();
        $province = $areaModel->where('id',$userInfo['province_id'])->value('shortname');
        $userInfo['province'] = $province;

        $city = $areaModel->where('id',$userInfo['city_id'])->value('shortname');
        $userInfo['city'] = $city;

        return $userInfo;
    }

    /**
     * 修改用户信息
     * @param int $id
     * @param array $param
     * @return true
     * @throws LogicException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateInfo(int $id,array $param)
    {
        $info = $this->model->where(['id'=>$id])->find();
        if (!$info) {
            throw new LogicException('用户不存在',400);
        }

        $updateData = [];
        if (isset($param['avatar'])) {
            $updateData['avatar'] = $param['avatar'];
        }
        if (isset($param['nickname'])) {
            $updateData['nickname'] = $param['nickname'];
        }
        if (isset($param['gender'])) {
            $updateData['gender'] = $param['gender'];
        }
        if (isset($param['age'])) {
            $updateData['age'] = $param['age'];
        }
        if (isset($param['height'])) {
            $updateData['height'] = $param['height'];
        }
        if (isset($param['weight'])) {
            $updateData['weight'] = $param['weight'];
        }
        if (isset($param['constellation'])) {
            $updateData['constellation'] = $param['constellation'];
        }
        if (isset($param['hobby'])) {
            $updateData['hobby'] = $param['hobby'];
        }
        if (isset($param['province_id'])) {
            $updateData['province_id'] = $param['province_id'];
        }
        if (isset($param['city_id'])) {
            $updateData['city_id'] = $param['city_id'];
        }

        try {
            $this->model->allowField(true)->save($updateData,['id'=>$id]);
        } catch (\Exception $e) {
            throw new LogicException('修改失败',400);
        }

        return true;
    }

}